/**
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/11/4 11:07
 */


class MyBlockingQueue{
    //保存数据本体
    private int[] data = new int[1000];
    //有效元素个数
    private int size = 0;
    //队首下标
    private int head = 0;
    //队尾下标
    private int tail = 0;

    //入队操作
    public void put(int value) throws InterruptedException {
        synchronized (this) {
            if (size == data.length) {
                this.wait();
            }
            data[tail] = value;
            tail++;
            //tail到达数组末尾的情况
            if (tail >= data.length) {
                tail = 0;
            }
//        tail = tail% data.length;//求余，也可以实现
            size++;//修改元素个数
            //put 成功后唤醒 take中的阻塞
            this.notify();
        }
    }
    //出队列
    public Integer take() throws InterruptedException {
        synchronized (this) {
            if (size == 0) {
//                return null;
                this.wait();
            }
            //取出 head 位置的元素
            int ret = data[head];
            head++;
            if (head >= data.length) {
                head = 0;
            }
            size--;
            //take 成功后唤醒 wait
            this.notify();
            return ret;
        }
    }
    }

public class Test {
    private static MyBlockingQueue queue = new MyBlockingQueue();

    public static void main(String[] args) {
        //生产者
        Thread producer = new Thread(()->{
            int num = 0;
            while (true){
                try {
                    System.out.println("生产了："+num);
                    queue.put(num);
                    num++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        producer.start();

        //消费者
        Thread customer = new Thread(()->{
           while (true){
               int num = 0;
               try {
                   num = queue.take();
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
               System.out.println("消费了："+num);
               try {
                   Thread.sleep(1000);
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        customer.start();










        // MyBlockingQueue queue = new MyBlockingQueue();
//        queue.put(1);
//        queue.put(2);
//        queue.put(3);
//        queue.put(4);
//        queue.put(5);
//        int ret = queue.take();
//        System.out.println(ret);

    }
}
